package thinker.miracle.business.user.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import thinker.miracle.business.user.dao.UserLoginLogDao;
import thinker.miracle.business.user.entity.UserLoginLogEntity;
import thinker.miracle.utils.DateUtil;
import thinker.miracle.utils.MathUtil;


/**
 * @author bo.chen
 *
 */
@Service
public class UserLoginLogService {
	
	@Autowired
	UserLoginLogDao userLoginLogDao;

	/**
	 * 保存用户登录记录
	 * 
	 * @param userLoginLog
	 */
	@Transactional
	public void save(UserLoginLogEntity userLoginLog) {
		if(userLoginLog != null && userLoginLog.getId() != null){
			userLoginLogDao.updateSelective(userLoginLog);
		}else if(userLoginLog != null && userLoginLog.getId() == null){
			userLoginLogDao.insert(userLoginLog);
		}else{
			throw new RuntimeException("user login log save exception");
		}
	}

	/**
	 * 重置tocken值
	 * 
	 * @param userLoginLog
	 * @return
	 */
	@Transactional
	public UserLoginLogEntity restCreateTocken(UserLoginLogEntity userLoginLog){
		synchronized (this) {
			if(userLoginLog != null && userLoginLog.getUserId() != null){
				userLoginLog.setTocken(MathUtil.randomNumAndString(32));
				UserLoginLogEntity userLoginLogTemp = getLastLoginLog(userLoginLog.getUserId());
				if(userLoginLogTemp != null){
					UserLoginLogEntity userLoginTemp = new UserLoginLogEntity();
					userLoginTemp.setUserId(userLoginLog.getUserId());
					userLoginTemp.setUpdateTime(DateUtil.getTime());
					userLoginTemp.setIsUse("0");
					userLoginLogDao.updateIsUseByUserId(userLoginTemp);//将原来的tocken标记为无效
				}
				save(userLoginLog);//重新生成tocken记录
			}
		}
		return userLoginLog;
	}
	
	
	/**
	 * 获取最近一次登陆记录
	 * 
	 * @param userId
	 * @return
	 */
	public UserLoginLogEntity getLastLoginLog(String userId){
		List<UserLoginLogEntity> userLoginLogs = userLoginLogDao.fingByUserId(userId);
		if(userLoginLogs != null && userLoginLogs.size() >=1){
			return userLoginLogs.get(0);
		}
		return null;
	}

	public UserLoginLogEntity getByTocken(String tocken) {
		List<UserLoginLogEntity> userLoginLogs = userLoginLogDao.findByUsedTocken(tocken);
		if(userLoginLogs != null && userLoginLogs.size() >=1){
			return userLoginLogs.get(0);
		}
		return null;
	}
	
}